package com.stujyh;

import com.stujyh.annotation.Compent;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Test {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        // 包名为："com.stujyh.bean"下，所有带compent注解的，利用反射机制创建对象
        String packageName = "com.stujyh.bean";
        String packagePath = packageName.replaceAll("\\.", "/");
        URL url = ClassLoader.getSystemClassLoader().getResource(packagePath);
        String path = url.getPath();
        File file = new File(path);
        File[] files = file.listFiles();
        Arrays.stream(files).forEach(f -> {
            try {
                String simpleName = f.getName().split("\\.")[0];
                String className = packageName + "." + simpleName;
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(Compent.class)) {
                    //存在注解
                    Compent annotation = aClass.getAnnotation(Compent.class);
                    String value = annotation.value();

                    Object object = aClass.newInstance();
                    map.put(value,object);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        System.out.println(map);
    }
}
